

<!DOCTYPE html>
<html lang="en" color-mode=light>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>dispatch_group同步异常问题 - 习武的个人博客</title>
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="google" content="notranslate" />
  
  <meta name="description" content="这次需要在这里梳理一下使用dispatch_group...">
  <meta name="author" content="习武">
  <link rel="icon" href="/xiwu_see/images/icons/favicon-16x16.png" type="image/png" sizes="16x16">
  <link rel="icon" href="/xiwu_see/images/icons/favicon-32x32.png" type="image/png" sizes="32x32">
  <link rel="apple-touch-icon" href="/xiwu_see/images/icons/apple-touch-icon.png" sizes="180x180">
  <meta rel="mask-icon" href="/xiwu_see/images/icons/stun-logo.svg" color="#333333">
  
    <meta rel="msapplication-TileImage" content="/xiwu_see/images/icons/favicon-144x144.jpeg">
    <meta rel="msapplication-TileColor" content="#000000">
  

  
<link rel="stylesheet" href="/xiwu_see/css/style.css">


  
    
<link rel="stylesheet" href="//at.alicdn.com/t/font_1445822_s6x2xcokxrl.css">

  

  
    
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css">

  

  
    
      
        
        
<link rel="stylesheet" href="https://cdn.bootcss.com/highlight.js/9.18.1/styles/xcode.min.css" name="highlight-style" mode="light">

      
        
        
<link rel="stylesheet" href="https://cdn.bootcss.com/highlight.js/9.18.1/styles/solarized-dark.min.css" name="highlight-style" mode="dark">

      
  

  <script>
    var CONFIG = window.CONFIG || {};
    var ZHAOO = window.ZHAOO || {};
    CONFIG = {
      isHome: false,
      fancybox: true,
      pjax: false,
      lazyload: {
        enable: true,
        only_post: 'false',
        loading: '/xiwu_see/images/theme/loading.gif'
      },
      donate: {
        enable: false,
        alipay: 'https://pic.izhaoo.com/alipay.jpg',
        wechat: 'https://pic.izhaoo.com/wechat.jpg'
      },
      galleries: {
        enable: true
      },
      fab: {
        enable: true,
        always_show: false
      },
      carrier: {
        enable: true
      },
      daovoice: {
        enable: false
      },
      preview: {
        background: {
          default: '/xiwu_see/images/theme/welcome-image.jpg',
          api: ''
        },
        motto: {
          default: '我在开了灯的床头下，想问问自己的心啊。',
          api: 'https://v2.jinrishici.com/one.json',
          data_contents: '["data","content"]'
        },
      },
      qrcode: {
        enable: false,
        type: 'url',
        image: 'https://pic.izhaoo.com/weapp-code.jpg',
      },
      toc: {
        enable: true
      },
      scrollbar: {
        model: 'simple'
      },
      notification: {
        enable: false,
        delay: 4500,
        list: '',
        page_white_list: '',
        page_black_list: ''
      }
    }
  </script>

  

  

<meta name="generator" content="Hexo 5.3.0"></head>

<body class="lock-screen">
  <div class="loading"></div>
  


  <nav class="navbar">
    <div class="left">
      
      
        <i class="iconfont iconmoono" id="color-toggle" color-toggle="light"></i>
      
    </div>
    <div class="center">dispatch_group同步异常问题</div>
    <div class="right">
      <i class="iconfont iconmenu j-navbar-menu"></i>
    </div>
    
  </nav>

  

<nav class="menu">
  <div class="menu-wrap">
    <div class="menu-close">
      <i class="iconfont iconbaseline-close-px"></i>
    </div>
    <ul class="menu-content"><li class="menu-item">
        <a href="/xiwu_see/ " class="underline "> 首页</a>
      </li><li class="menu-item">
        <a href="/xiwu_see/archives/ " class="underline "> 归档</a>
      </li><li class="menu-item">
        <a href="/xiwu_see/tags/ " class="underline "> 标签</a>
      </li><li class="menu-item">
        <a href="/xiwu_see/categories/ " class="underline "> 分类</a>
      </li><li class="menu-item">
        <a href="/xiwu_see/about/ " class="underline "> 关于</a>
      </li></ul>
    
      <div class="menu-copyright"><p>Powered by <a target="_blank" href="https://hexo.io">习武</a>  |  Theme - <a target="_blank" href="https://xiwu123.gitee.io/xiwu_see">习武的个人博客</a></p></div>
    
  </div>
</nav>
  <main id="main">
  <div class="article-wrap">
    <div class="row container">
      <div class="col-xl-3"></div>
      <div class="col-xl-6"><article class="article">
  <div class="wrap">
    <section class="head">
  <img   class="lazyload" data-original="/xiwu_see/images/theme/theme-iOS-9.jpg" src=""  draggable="false">
  <div class="head-mask">
    <h1 class="head-title">dispatch_group同步异常问题</h1>
    <div class="head-info">
      <span class="post-info-item"><i class="iconfont iconcalendar"></i>April 01, 2020</span>
      
      <span class="post-info-item"><i class="iconfont iconfont-size"></i>9561</span>
    </div>
  </div>
</section>
    <section class="main">
      <section class="content">
        <p>这次需要在这里梳理一下使用dispatch_group_t引起的同步异常问题，具体问题请看下面:</p>
<figure class="highlight apache"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs apache"><span class="hljs-comment">#0 Thread</span><br><span class="hljs-attribute">SIGSEGV</span><br><span class="hljs-attribute">SEGV_ACCERR</span><br><br><span class="hljs-attribute">libdispatch</span>.dylib   _dispatch_group_leave$VARIANT$armv<span class="hljs-number">81</span> + <span class="hljs-number">8</span><br><span class="hljs-attribute">Shikamaru</span>   __<span class="hljs-number">57</span>-[SKMCommunityCircleListViewController loadCircleDataNum]_block_invoke (SKMCommunityCircleListViewController.m:<span class="hljs-number">77</span>)<br><span class="hljs-attribute">Shikamaru</span>   __<span class="hljs-number">43</span>-[SKMCirclePageViewModel requestCircleNum:]_block_invoke (SKMCirclePageViewModel.m:<span class="hljs-number">218</span>)<br><span class="hljs-attribute">Shikamaru</span>   __<span class="hljs-number">48</span>-[YTKNetworkAgent requestDidSucceedWithRequest:]_block_invoke (YTKNetworkAgent.m:<span class="hljs-number">387</span>)<br><span class="hljs-attribute">libdispatch</span>.dylib   __dispatch_call_block_and_release + <span class="hljs-number">24</span><br><span class="hljs-attribute">libdispatch</span>.dylib   __dispatch_client_callout + <span class="hljs-number">16</span><br><span class="hljs-attribute">libdispatch</span>.dylib   __dispatch_main_queue_callback_<span class="hljs-number">4</span>CF$VARIANT$armv<span class="hljs-number">81</span> + <span class="hljs-number">1008</span><br><span class="hljs-attribute">CoreFoundation</span>  ___CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + <span class="hljs-number">12</span><br><span class="hljs-attribute">CoreFoundation</span>  ___CFRunLoopRun + <span class="hljs-number">1924</span><br><span class="hljs-attribute">CoreFoundation</span>  CFRunLoopRunSpecific + <span class="hljs-number">436</span><br><span class="hljs-attribute">GraphicsServices</span>    GSEventRunModal + <span class="hljs-number">104</span><br><span class="hljs-attribute">UIKitCore</span>   UIApplicationMain + <span class="hljs-number">212</span><br><span class="hljs-attribute">Shikamaru</span>   main (main.m:<span class="hljs-number">14</span>)<br><span class="hljs-attribute">libdyld</span>.dylib   _start + <span class="hljs-number">4</span><br></code></pre></td></tr></table></figure>
<p>从中可以看出这里出现的异常信号SIGSEGV属于野指针信号，意思是程序无效内存中止信号，一般是表示内存不合法，二是产生的错误信息，也指向 _dispatch_group_leave$VARIANT$armv81 + 8，为了解决这个问题，那么这里进行了如下的流程分析：  </p>
<ul>
<li>检查代码是否实现了dispatch_group_enter和dispatch_group_leave的配对；</li>
<li>存在请求回调block造成了dispatch_group_enter和dispatch_group_leave的配对数量差；</li>
<li>dispatch_group_enter和dispatch_group_leave的配对数量差造成的异常与引言异常的流程对比；</li>
<li>其他使用dispatch_group未发生异常的比较；</li>
<li>group为空造成的异常与引言异常的流程对比；</li>
<li>引起为空的条件和场景，实际测试；</li>
<li>整体项目整改；</li>
</ul>
<hr>
<h3 id="分析过程"><a href="#分析过程" class="headerlink" title="分析过程"></a>分析过程</h3><h4 id="代码逻辑配对分析"><a href="#代码逻辑配对分析" class="headerlink" title="代码逻辑配对分析"></a>代码逻辑配对分析</h4><p>通过该控制器vc的整体代码逻辑分析，这里是将group对象当作全局对象，然后将每一个请求当作方法进行了拆分，主要是为了方法重用性和独立性，那么也就是说这种方式不太可能出现配对的误差。</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs csharp">- (<span class="hljs-keyword">void</span>)loadAllData &#123;<br>    self.circleVM.postNextId = nil;<br>    [<span class="hljs-meta">self resetPlayerAction</span>];<br>    [<span class="hljs-meta">MBProgressHUD showMessage:@<span class="hljs-meta-string">&quot;请稍等...&quot;</span></span>];<br><br>    [<span class="hljs-meta">self loadCircleData</span>];<br><br>    [<span class="hljs-meta">self loadPostDataByArticleId</span>];<br><br>    [<span class="hljs-meta">self loadPostData:YES</span>];<br><br>    SKMWeakSelf<br>    dispatch_group_notify(self.<span class="hljs-keyword">group</span>, dispatch_get_main_queue(), ^&#123;<br>        SKMStrongSelf<br>        [<span class="hljs-meta">MBProgressHUD hideHUD</span>];<br>        [<span class="hljs-meta">strongSelf.dataSource removeAllObjects</span>];<br>        <span class="hljs-keyword">if</span> (strongSelf.circleVM.circleList) &#123;<br>            [<span class="hljs-meta">strongSelf.dataSource addObject:strongSelf.circleVM.circleList</span>];<br>        &#125;<br>        <span class="hljs-keyword">if</span> (strongSelf.headerModel) &#123;<br>            [<span class="hljs-meta">strongSelf.dataSource addObject:strongSelf.headerModel</span>];<br>        &#125;<br>        [<span class="hljs-meta">strongSelf.dataSource addObjectsFromArray:strongSelf.circleVM.postArr</span>];<br>        strongSelf.dataArr = strongSelf.dataSource;<br>        [<span class="hljs-meta">strongSelf actionWithRefresh</span>];<br>        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(<span class="hljs-number">0.5</span> * NSEC_PER_SEC)), dispatch_get_main_queue(), ^&#123;<br>           [<span class="hljs-meta">strongSelf handleScrollPlay</span>];<br>        &#125;);<br>    &#125;);<br>&#125;<br></code></pre></td></tr></table></figure>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs objectivec">- (<span class="hljs-keyword">void</span>)loadCircleData &#123;<br>    dispatch_group_enter(<span class="hljs-keyword">self</span>.group);<br>    <span class="hljs-built_in">SKMWeakSelf</span><br>    [<span class="hljs-keyword">self</span>.circleVM requestCircleFirstPageList:^(<span class="hljs-built_in">SKMCircleInfoListModel</span> *circleList, <span class="hljs-built_in">NSError</span> * _Nonnull error) &#123;<br>        <span class="hljs-built_in">SKMStrongSelf</span><br>        <span class="hljs-keyword">if</span> (strongSelf) &#123;<br>            dispatch_group_leave(strongSelf.group);<br>        &#125;<br>    &#125;];<br>&#125;<br></code></pre></td></tr></table></figure>
<p>剩下的就不一一举出了，看得出来代码逻辑上配对是没有问题的。</p>
<hr>
<h4 id="运行实际的配对分析"><a href="#运行实际的配对分析" class="headerlink" title="运行实际的配对分析"></a>运行实际的配对分析</h4><p>这里的本意是存在请求的block回调没有调用或者多次调用造成了配对误差，这种猜想是根据如下信息资料来的。</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs objectivec"><span class="hljs-built_in">NSArray</span> *imageURLArray = @[<span class="hljs-string">@&quot;1&quot;</span>, <span class="hljs-string">@&quot;2&quot;</span>, <span class="hljs-string">@&quot;3&quot;</span>, <span class="hljs-string">@&quot;4&quot;</span>];<br>dispatch_group_t group = dispatch_group_create();<br>[imageURLArray enumerateObjectsUsingBlock:^(<span class="hljs-keyword">id</span>  _Nonnull obj, <span class="hljs-built_in">NSUInteger</span> idx, <span class="hljs-built_in">BOOL</span> * _Nonnull stop) &#123;<br>        dispatch_group_enter(group);<br>        [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[<span class="hljs-built_in">NSURL</span> URLWithString:imageURLArray[idx]] options:SDWebImageDownloaderLowPriority progress:<span class="hljs-literal">nil</span> completed:^(<span class="hljs-built_in">UIImage</span> * _Nullable image, <span class="hljs-built_in">NSData</span> * _Nullable data, <span class="hljs-built_in">NSError</span> * _Nullable error, <span class="hljs-built_in">BOOL</span> finished) &#123;<br>            dispatch_group_leave(group);<br>            <span class="hljs-built_in">NSLog</span>(<span class="hljs-string">@&quot;idx:%zd&quot;</span>,idx);<br>        &#125;];<br>    &#125;];<br>    dispatch_group_notify(group, dispatch_get_main_queue(), ^&#123;<br>        <span class="hljs-built_in">NSLog</span>(<span class="hljs-string">@&quot;%@&quot;</span>, imageURLArray);<br>    &#125;);<br></code></pre></td></tr></table></figure>
<blockquote>
<p>代码逻辑可以说是很简单：一个图片URL数组。使用SDWebImage多线程进行并发下载，直到所有图片都下载完成进行回调。但是就是这样一段代码居然会偶尔出现崩溃，和项目中其他地方使用到dispatch_group的地方进行过比较，也没发现有什么不同，没办法这时候只有先去看看dispatch_group的源码了,其中有一段是这样的。</p>
</blockquote>
<figure class="highlight reasonml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs reasonml">dispatch<span class="hljs-constructor">_group_leave(<span class="hljs-params">dispatch_group_t</span> <span class="hljs-params">dg</span>)</span> &#123;<br>    dispatch_semaphore_t dsema = (dispatch_semaphore_t)dg;<br>    dispatch<span class="hljs-constructor">_atomic_release_barrier()</span>;<br>    long value = dispatch<span class="hljs-constructor">_atomic_inc2o(<span class="hljs-params">dsema</span>, <span class="hljs-params">dsema_value</span>)</span>;<br>    <span class="hljs-keyword">if</span> (slowpath(value<span class="hljs-operator"> == </span>LONG_MIN)) &#123;<br>        <span class="hljs-constructor">DISPATCH_CLIENT_CRASH(<span class="hljs-string">&quot;Unbalanced call to dispatch_group_leave()&quot;</span>)</span>;<br>    &#125;<br>    <span class="hljs-keyword">if</span> (slowpath(value<span class="hljs-operator"> == </span>dsema-&gt;dsema_orig)) &#123;<br>        (void)<span class="hljs-constructor">_dispatch_group_wake(<span class="hljs-params">dsema</span>)</span>;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<blockquote>
<p>通过源代码我们发现在调用dispatch_group_leave的时候是可能会发生crash的，这段代码的重点就是当这个value值和LONG_MIN相等的时候，这里会发生crash。我们需要关注下LONG_MIN这个数字，LONG_MIN = -LONG_MAX - 1。在dispatch_group_create里面发现了它的踪影：</p>
</blockquote>
<figure class="highlight reasonml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs reasonml">dispatch_group_t<br>dispatch<span class="hljs-constructor">_group_create(<span class="hljs-params">void</span>)</span>&#123;<br>    dispatch_group_t dg = <span class="hljs-constructor">_dispatch_alloc(DISPATCH_VTABLE(<span class="hljs-params">group</span>)</span>,sizeof(<span class="hljs-keyword">struct</span> dispatch_semaphore_s));<br>    <span class="hljs-constructor">_dispatch_semaphore_init(LONG_MAX, <span class="hljs-params">dg</span>)</span>;<br>    return dg;<br>&#125;<br></code></pre></td></tr></table></figure>
<blockquote>
<p>这两段代码的结合告诉了我们一个事实：当dq这个信号量加一导致溢出后，dispatch_group_leave就会Crash。通过查阅SDWebImageDownloader.m源码发现：</p>
</blockquote>
<figure class="highlight erlang-repl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs erlang-repl">dispatch_barrier_sync(self.barrierQueue, ^&#123;<br>    SDWebImageDownloaderOperation *operation = self.URLOperations[url];<br>    if (!operation) &#123;<br>    operation = createCallback();<br><br>    // !!!!!!!特别注意这行!!!!!!!!!<br>    self.URLOperations[url] = operation;<br><br>    __weak SDWebImageDownloaderOperation *woperation = operation;<br>    operation.completionBlock = ^&#123;<br>      SDWebImageDownloaderOperation *soperation = woperation;<br>      if (!soperation) return;<br>      if (self.URLOperations[url] == soperation) &#123;<br>          [self.URLOperations removeObjectForKey:url];<br>      &#125;;<br>    &#125;;<br>&#125;<br></code></pre></td></tr></table></figure>
<blockquote>
<p>SDWebImage的下载器会根据URL做下载任务对应NSOperation映射，也即之前创建的下载回调Block。好，就是这行导致Crash的发生。为什么呢？<br>因为SDWebImage的下载器会根据URL做下载任务对应NSOperation映射，相同的URL会映射到同一个未执行的NSOperation。那么通过代码我当A组图片下载完成后，相同的url 回调是B组内 而不是A组内。此时B的计数为4 。当B 图片下载完后，结束计数为 5 。因为B图片enter 的次数为4 ,leave 的次数为5 ,因此会崩溃！</p>
</blockquote>
<p>下面我们在看代码分析里面使用组的情况是AFN请求，那么会不会AFN请求也发生了类似回调block替换的情况，请看源码。</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs objectivec">- (<span class="hljs-keyword">void</span>)setDelegate:(AFURLSessionManagerTaskDelegate *)delegate<br>            forTask:(<span class="hljs-built_in">NSURLSessionTask</span> *)task<br>&#123;<br>    <span class="hljs-built_in">NSParameterAssert</span>(task);<br>    <span class="hljs-built_in">NSParameterAssert</span>(delegate);<br><br>    [<span class="hljs-keyword">self</span>.lock lock];<br><span class="hljs-comment">//注意这行，进行回调的代理使用了task.taskIdentifier标识</span><br>    <span class="hljs-keyword">self</span>.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate;<br>    [<span class="hljs-keyword">self</span> addNotificationObserverForTask:task];<br>    [<span class="hljs-keyword">self</span>.lock unlock];<br>&#125;<br></code></pre></td></tr></table></figure>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs objectivec"><span class="hljs-class"><span class="hljs-keyword">@interface</span> <span class="hljs-title">NSURLSessionTask</span> : <span class="hljs-title">NSObject</span> &lt;<span class="hljs-title">NSCopying</span>, <span class="hljs-title">NSProgressReporting</span>&gt;</span><br><span class="hljs-comment">//task标识是一个数字型</span><br><span class="hljs-keyword">@property</span> (<span class="hljs-keyword">readonly</span>)                 <span class="hljs-built_in">NSUInteger</span>    taskIdentifier;    <span class="hljs-comment">/* an identifier for this task, assigned by and unique to the owning session */</span><br><span class="hljs-keyword">@property</span> (<span class="hljs-keyword">nullable</span>, <span class="hljs-keyword">readonly</span>, <span class="hljs-keyword">copy</span>) <span class="hljs-built_in">NSURLRequest</span>  *originalRequest;  <span class="hljs-comment">/* may be nil if this is a stream task */</span><br><span class="hljs-keyword">@property</span> (<span class="hljs-keyword">nullable</span>, <span class="hljs-keyword">readonly</span>, <span class="hljs-keyword">copy</span>) <span class="hljs-built_in">NSURLRequest</span>  *currentRequest;   <span class="hljs-comment">/* may differ from originalRequest due to http server redirection */</span><br><span class="hljs-keyword">@property</span> (<span class="hljs-keyword">nullable</span>, <span class="hljs-keyword">readonly</span>, <span class="hljs-keyword">copy</span>) <span class="hljs-built_in">NSURLResponse</span> *response;         <span class="hljs-comment">/* may be nil if no response has been received */</span><br></code></pre></td></tr></table></figure>
<p>也就是说AFN的每个请求都会分配一个数字标识进行回调区分，不可能发生类似SDWebImage类似的情况。那么现在从原理上确认group请求的配对不会发生异常。</p>
<hr>
<h4 id="异常结果对比"><a href="#异常结果对比" class="headerlink" title="异常结果对比"></a>异常结果对比</h4><p>我们再确认一下配对造成的异常与实际异常结果的对比，可以在对应的请求里多进行一次dispatch_group_leave操作，造成crash，看看异常堆栈信息。</p>
<p><img   class="lazyload" data-original="/xiwu_see/images/iOS/dispatch_group_crash.jpeg" src="" ></p>
<blockquote>
<p>看起来是不是与引言里的bug堆栈信息很类似，那就是配对问题，但是前面我们已经确认配对不可能出现问题，但是别急，我们还需要再确认一下异常信号信息。我们发现这里发生crash后抛出的是<code>Thread 1: EXC_BREAKPOINT (code=1, subcode=0x10b4abf20)</code>信息，意思是由断点指令或其它trap指令产生，产生了异常中断信号，不对呀，这与实际结果的野指针信号不匹配呀。所以我们可以进一步确认异常的产生不是因为配对的问题。</p>
</blockquote>
<hr>
<h4 id="与其他使用diaptch-group但未发生异常的对比"><a href="#与其他使用diaptch-group但未发生异常的对比" class="headerlink" title="与其他使用diaptch_group但未发生异常的对比"></a>与其他使用diaptch_group但未发生异常的对比</h4><figure class="highlight pf"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><code class="hljs pf">dispatch_group_t <span class="hljs-keyword">group</span> = dispatch_group_create();<br>    SKMWeakSelf<br>    dispatch_group_enter(<span class="hljs-keyword">group</span>);<br>    [<span class="hljs-literal">self</span>.viewModel requestSurroundList:<span class="hljs-literal">self</span>.params completeBlock:^(SkmrSurroundInfoRsp *skmrSurroundInfoRsp, NSError * _Nonnull error) &#123;<br>        dispatch_group_leave(<span class="hljs-keyword">group</span>);<br>        if (skmrSurroundInfoRsp) &#123;<br>            SKMStrongSelf<br>            strongSelf.skmrSurroundInfoRsp = skmrSurroundInfoRsp;<br>            [strongSelf.<span class="hljs-built_in">table</span>View reloadData];<br>        &#125;<br>    &#125;];<br>    dispatch_group_enter(<span class="hljs-keyword">group</span>);<br>    [<span class="hljs-literal">self</span>.viewModel requestSearchCommunityList:<span class="hljs-literal">self</span>.params completeBlock:^(SkmrCommunityListRsp *skmrCommunityListRsp, NSError * _Nonnull error) &#123;<br>        dispatch_group_leave(<span class="hljs-keyword">group</span>);<br>        SKMStrongSelf<br>        if (skmrCommunityListRsp) &#123;<br>            strongSelf.skmrCommunityListRsp = skmrCommunityListRsp;<br>            [strongSelf.<span class="hljs-built_in">table</span>View reloadData];<br>        &#125;<br>    &#125;];<br>    dispatch_group_notify(<span class="hljs-keyword">group</span>, dispatch_get_main_queue(), ^&#123;<br>        SKMStrongSelf<br>        [strongSelf judgeNoResultAction];<br>        [strongSelf actionWithRefresh:YES];<br>    &#125;);<br></code></pre></td></tr></table></figure>
<blockquote>
<p>上述是未发生异常的 dispatch_group的使用用法,是不是已经发现问题了，一个是局部定义的group，产生问题的使用的是全局定义的group,多了一个当前self的强引用。那么可以猜想的问题就只剩下一个了那就是self有可能为nil,那么下一步就是进行验证了，执行<code>dispatch_group_leave(nil)</code>。</p>
</blockquote>
<h4 id="验证group为nil的结果对比"><a href="#验证group为nil的结果对比" class="headerlink" title="验证group为nil的结果对比"></a>验证group为nil的结果对比</h4><p><img   class="lazyload" data-original="/xiwu_see/images/iOS/dispatch_group_nil.jpeg" src="" ></p>
<blockquote>
<p>从图中也可以看出发生crash的流程一致，而且发出的异常信号是<code>EXC_BAD_ACCESS</code>，这是一个非法访问已经释放内存区域的异常，与原结论的SIGSEGV信号一致，那么大体上可以确认该异常起因就是这个。</p>
</blockquote>
<hr>
<h4 id="引起为空的条件和场景"><a href="#引起为空的条件和场景" class="headerlink" title="引起为空的条件和场景"></a>引起为空的条件和场景</h4><p>上述告知了我们引起异常的原因是<code>dispatch_group_leave(nil)</code>了，那么为什么group为nil，也就是为什么self为nil，什么况下self为nil了但是block还会执行，加上这是在一个请求方法里面，那么就很容易猜想，控制器vc本身(self)推出释放了，但是请求已经发出，当然block回调还是会继续执行。而且要达到这种效果要么就是用户很快进来，未等请求完成立马退出，但是平常我们测试的网速都是很快的，要想实践出来，当然必须要靠弱网测试了。</p>
<p><img   class="lazyload" data-original="/xiwu_see/images/iOS/dispatch_group_weaknet.jpeg" src="" ></p>
<blockquote>
<p>图中可以看到设置成弱网请求后确实可以达成实现了我们的猜想，也复现了异常产生的场景。那么下一步就是如何解决了。实际上很简单了，那就是在执行<code>dispatch_group_leave(nil)</code>前我们先要做self的空判断，不为空则执行，否则直接跳过，经实际测试，可行，app正常运行。至此，关于异常的处理基本结束。</p>
</blockquote>
<hr>
<h4 id="完整项目收尾"><a href="#完整项目收尾" class="headerlink" title="完整项目收尾"></a>完整项目收尾</h4><p>上面已经分析了异常的分析流程、场景和解决方案，那么为了全面考虑，是否存在漏网之鱼，所以需要整体项目更改，但是这里为什么全局的group和局部定义的group区别这么大，按照原理是方法执行完后，局部变量自动释放，生命周期只在该方法内，所以用弱网环境验证一下，我们执行同样进来控制器vc不等请求完成立马退出，断点，结果如下。</p>
<p><img   class="lazyload" data-original="/xiwu_see/images/iOS/dispatch_group_aspect.jpeg" src="" ></p>
<blockquote>
<p>OK，发现控制器释放了，但是group依然存在，那么说明局部变量应该是block在运行时直接将group复制到了堆内存，其内存管理由block生命周期管理，而前者全局变量group由vc进行了强引用，其生命周期由vc控制，vc释放了，group自然也销毁了。所以两者才会存在同一场景上造成结果的不同。</p>
</blockquote>
<hr>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><ul>
<li>dispatch_group_enter和dispatch_group_leave的配对必须配对。</li>
<li>注意使用dispatch_group时第三方库的影响。</li>
<li>注意group生命周期的管理，特别是弱网环境下的影响。</li>
</ul>

      </section>
      <section class="extra">
        
          <ul class="copyright">
  
    <li><strong>本文作者：</strong>习武</li>
    <li><strong>本文链接：</strong><a href="https://gitee.com/xiwu123/xiwu_see.git/2020/04/01/iOS/dispatch_group%E5%BC%95%E8%B5%B7%E7%9A%84%E5%BC%82%E5%B8%B8/index.html" title="https:&#x2F;&#x2F;gitee.com&#x2F;xiwu123&#x2F;xiwu_see.git&#x2F;2020&#x2F;04&#x2F;01&#x2F;iOS&#x2F;dispatch_group%E5%BC%95%E8%B5%B7%E7%9A%84%E5%BC%82%E5%B8%B8&#x2F;index.html">https:&#x2F;&#x2F;gitee.com&#x2F;xiwu123&#x2F;xiwu_see.git&#x2F;2020&#x2F;04&#x2F;01&#x2F;iOS&#x2F;dispatch_group%E5%BC%95%E8%B5%B7%E7%9A%84%E5%BC%82%E5%B8%B8&#x2F;index.html</a></li>
    <li><strong>版权声明：</strong>本博客所有文章均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" title="BY-NC-SA" target="_blank" rel="noopener">BY-NC-SA</a> 许可协议，转载请注明出处！</li>
  
</ul>
        
        
        
  <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/xiwu_see/tags/dispatch-group-%E5%BC%82%E5%B8%B8-%E5%A4%9A%E7%BA%BF%E7%A8%8B-%E5%90%8C%E6%AD%A5/" rel="tag">dispatch_group, 异常, 多线程, 同步</a></li></ul> 

        
  <nav class="nav">
    <a href="/xiwu_see/2020/04/09/iOS/%E7%9B%B8%E5%86%8C%E6%B5%8F%E8%A7%88%E5%99%A8%E4%BD%BF%E7%94%A8%E6%89%8B%E5%86%8C/"><i class="iconfont iconleft"></i>相册浏览器使用手册</a>
    <a href="/xiwu_see/2020/04/01/iOS/%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%90%8C%E6%AD%A5%E4%BD%BF%E7%94%A8/">多线程同步<i class="iconfont iconright"></i></a>
  </nav>

      </section>
      
    </section>
  </div>
</article></div>
      <div class="col-xl-3">
        
          
  <aside class="toc-wrap">
    <h3 class="toc-title">文章目录：</h3>
    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%86%E6%9E%90%E8%BF%87%E7%A8%8B"><span class="toc-text">分析过程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-text">总结</span></a></li></ol>
  </aside>

        
      </div>
    </div>
  </div>
</main>
  

<footer class="footer">
  <div class="footer-social"><a 
        href="tencent://message/?Menu=yes&uin=756364924 "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#12B7F5'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  iconQQ "></i>
      </a><a 
        href="javascript:; "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#09BB07'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  iconwechat-fill "></i>
      </a><a 
        href="https://github.com/xiwuxisheng "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#9f7be1'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  icongithub-fill "></i>
      </a><a 
        href="756364924@qq.com "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color=#FF3B00" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  iconmail"></i>
      </a></div>
  
    <div class="footer-copyright"><p>Powered by <a target="_blank" href="https://hexo.io">习武</a>  |  Theme - <a target="_blank" href="https://xiwu123.gitee.io/xiwu_see">习武的个人博客</a></p></div>
  
</footer>
  
      <div class="fab fab-plus">
    <i class="iconfont iconplus"></i>
  </div>
  
  
  <div class="fab fab-up">
    <i class="iconfont iconcaret-up"></i>
  </div>
  
  
    <div class="scrollbar j-scrollbar">
  <div class="scrollbar-current j-scrollbar-current"></div>
</div>
  
  
    
<script src="/xiwu_see/js/color-mode.js"></script>

  
</body>

<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>



  
<script src="https://cdn.bootcdn.net/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>




  
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js"></script>








<script src="/xiwu_see/js/utils.js"></script>
<script src="/xiwu_see/js/script.js"></script>





  <script>
    (function () {
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
      } else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
      }
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>













</html>